import { Modal, Form, Input, Select, message } from 'antd';

import userService from '@/api/services/security/userService';
import { UploadAvatar } from '@/components/upload';

import { ModalProps, UserInfo } from '#/entity';
import { genderMapText } from '#/publicVariable';

export default function UserDetail({
  show,
  onCancel,
  title,
  onOk,
  formValue,
}: ModalProps<UserInfo>) {
  const [form] = Form.useForm();
  const onFinish = (values: any) => {
    const transData = {
      ...values,
      parent: undefined,
    };
    if (formValue.id !== '0') {
      userService.updateUser(Number.parseInt(formValue.id, 10), transData).then(() => {
        message.success('更新成功');
        onOk();
      });
    } else {
      userService.createUser(transData).then(() => {
        message.success('创建成功');
        onOk();
      });
    }
  };
  const modalRender = (dom: React.ReactNode) => (
    <Form
      initialValues={formValue}
      form={form}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 18 }}
      onFinish={onFinish}
      clearOnDestroy
      layout="horizontal"
      // layout="vertical"
    >
      {dom}
    </Form>
  );
  return (
    <Modal
      okText="确定"
      cancelText="取消"
      title={title}
      open={show}
      onCancel={onCancel}
      okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
      destroyOnHidden
      modalRender={modalRender}
    >
      <Form.Item label="头像" name="portrait">
        <UploadAvatar
          defaultAvatar={formValue.portrait}
          onUploadSuccess={(files) => {
            form.setFieldValue('portrait', files);
          }}
        />
      </Form.Item>
      <Form.Item label="账号" name="code" rules={[{ required: true, message: '请输入账号' }]}>
        <Input disabled={formValue.id !== '0'} />
      </Form.Item>
      <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
        <Input />
      </Form.Item>
      <Form.Item
        label="邮箱"
        name="email"
        rules={[{ type: 'email', message: '请输入正确的邮箱格式' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="手机"
        name="mobile"
        rules={[
          { required: true, message: '请输入手机号' },
          {
            validator: (_, value) => {
              if (!value) {
                return Promise.resolve();
              }
              const pattern = /^1[3-9]\d{9}$/;
              if (!pattern.test(value)) {
                return Promise.reject(new Error('请输入正确的手机号格式'));
              }
              return Promise.resolve();
            },
          },
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item label="性别" name="gender" rules={[{ required: true, message: '请选择性别' }]}>
        <Select
          options={Object.entries(genderMapText).map(([value, label]) => ({
            value,
            label,
          }))}
        />
      </Form.Item>
    </Modal>
  );
}
